package com.cloud.phone.service;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.cloud.phone.R;

public class FloatWindowService extends Service {
    private WindowManager windowManager;
    private View floatView;
    private WindowManager.LayoutParams params;

    @Override
    public void onCreate() {
        super.onCreate();
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        floatView = new ImageView(this);
        floatView.setBackgroundResource(R.mipmap.ic_launcher);

        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        // 初始位置
        params.gravity = Gravity.START | Gravity.TOP;
        params.x = 100;
        params.y = 100;

        floatView.setOnTouchListener(new View.OnTouchListener() {
            private int lastX, lastY;
            private float startX, startY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        startX = event.getX();
                        startY = event.getY();
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        params.x += (int) (event.getRawX() - lastX);
                        params.y += (int) (event.getRawY() - lastY);
                        windowManager.updateViewLayout(floatView, params);
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        return true;
                    case MotionEvent.ACTION_UP:
                        // 吸附逻辑
                        // ...
                        return true;
                }
                return false;
            }
        });

        windowManager.addView(floatView, params);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (floatView != null) {
            windowManager.removeView(floatView);
        }
    }
}
